import { productApi } from '@/api'

// 商品模块状态管理
const state = {
  // 商品列表
  products: [],
  // 商品详情
  productDetail: null,
  // 商品分类
  categories: [],
  // 当前分类
  currentCategory: null,
  // 搜索关键词
  searchKeyword: '',
  // 排序方式
  sortBy: 'default',
  // 分页信息
  pagination: {
    current: 1,
    pageSize: 12,
    total: 0
  },
  // 加载状态
  loading: false
}

const mutations = {
  // 设置商品列表
  SET_PRODUCTS(state, products) {
    state.products = products
  },
  
  // 设置商品详情
  SET_PRODUCT_DETAIL(state, product) {
    state.productDetail = product
  },
  
  // 设置商品分类
  SET_CATEGORIES(state, categories) {
    state.categories = categories
  },
  
  // 设置当前分类
  SET_CURRENT_CATEGORY(state, category) {
    state.currentCategory = category
  },
  
  // 设置搜索关键词
  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword
  },
  
  // 设置排序方式
  SET_SORT_BY(state, sortBy) {
    state.sortBy = sortBy
  },
  
  // 设置分页信息
  SET_PAGINATION(state, pagination) {
    state.pagination = { ...state.pagination, ...pagination }
  },
  
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  // 添加商品到列表
  ADD_PRODUCT(state, product) {
    state.products.unshift(product)
  },
  
  // 更新商品信息
  UPDATE_PRODUCT(state, { id, updates }) {
    const index = state.products.findIndex(p => p.id === id)
    if (index !== -1) {
      state.products[index] = { ...state.products[index], ...updates }
    }
    
    // 如果更新的是当前商品详情，也更新详情
    if (state.productDetail && state.productDetail.id === id) {
      state.productDetail = { ...state.productDetail, ...updates }
    }
  },
  
  // 删除商品
  DELETE_PRODUCT(state, productId) {
    state.products = state.products.filter(p => p.id !== productId)
    
    // 如果删除的是当前商品详情，清空详情
    if (state.productDetail && state.productDetail.id === productId) {
      state.productDetail = null
    }
  }
}

const actions = {
  // 获取商品列表
  async fetchProducts({ commit, state }, { category = null, keyword = '', page = 1 } = {}) {
    commit('SET_LOADING', true)
    
    try {
      const response = await productApi.getProducts({ 
        category, 
        keyword, 
        page, 
        pageSize: state.pagination.pageSize 
      })
      
      if (response.code === 200) {
        commit('SET_PRODUCTS', response.data.list)
        commit('SET_PAGINATION', {
          current: response.data.page,
          total: response.data.total
        })
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '获取商品列表失败' }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取商品详情
  async fetchProductDetail({ commit }, productId) {
    commit('SET_LOADING', true)
    
    try {
      console.log('Vuex: 开始获取商品详情，ID:', productId)
      const response = await productApi.getProductDetail(productId)
      console.log('Vuex: API响应:', response)
      
      if (response.code === 200) {
        commit('SET_PRODUCT_DETAIL', response.data)
        console.log('Vuex: 商品详情已设置:', response.data)
        return { success: true, data: response.data }
      } else {
        console.log('Vuex: API返回错误:', response.message)
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('Vuex: 获取商品详情异常:', error)
      return { success: false, message: error.message || '获取商品详情失败' }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取商品分类
  async fetchCategories({ commit }) {
    try {
      const response = await productApi.getCategories()
      
      if (response.code === 200) {
        commit('SET_CATEGORIES', response.data)
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      return { success: false, message: error.message || '获取分类失败' }
    }
  },
  
  // 设置当前分类
  setCurrentCategory({ commit }, category) {
    commit('SET_CURRENT_CATEGORY', category)
  },
  
  // 设置搜索关键词
  setSearchKeyword({ commit }, keyword) {
    commit('SET_SEARCH_KEYWORD', keyword)
  },
  
  // 设置排序方式
  setSortBy({ commit }, sortBy) {
    commit('SET_SORT_BY', sortBy)
  }
}

const getters = {
  // 获取商品列表
  products: state => state.products,
  
  // 获取商品详情
  productDetail: state => {
    console.log('Vuex getter: productDetail 被调用，当前值:', state.productDetail)
    return state.productDetail
  },
  
  // 获取商品分类
  categories: state => state.categories,
  
  // 获取当前分类
  currentCategory: state => state.currentCategory,
  
  // 获取搜索关键词
  searchKeyword: state => state.searchKeyword,
  
  // 获取排序方式
  sortBy: state => state.sortBy,
  
  // 获取分页信息
  pagination: state => state.pagination,
  
  // 获取加载状态
  loading: state => state.loading,
  
  // 获取商品总数
  totalProducts: state => state.pagination.total,
  
  // 获取当前页商品
  currentPageProducts: state => state.products,
  
  // 检查是否有商品
  hasProducts: state => state.products.length > 0
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 